package com.joyoung.rxtx.controller;

import com.joyoung.rxtx.cache.StringResultCache;
import com.joyoung.rxtx.config.ParamConfig;
import com.joyoung.rxtx.exception.ComException;
import com.joyoung.rxtx.manager.RxtxManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@CrossOrigin
public class RxtxController {
    @Autowired
    private StringResultCache cache;
    @Autowired
    private RxtxManager rxtxManager;
    @Autowired
    private ParamConfig paramConfig;
    @GetMapping("query")
    public String query() throws ComException, InterruptedException {
        //代码执行时间
        Long startTime = System.currentTimeMillis();

        if(!StringUtils.isEmpty(cache.getResult()))
        {
            cache.setResult("");
        }
        rxtxManager.sendComm("49310001090004C74493");

        //机器与请求是异步的，所以要写while循环，保证线程等待
        while(true)
        {
            //当返回结果是246位证明正常返回
            if (!StringUtils.isEmpty(cache.getResult()) && cache.getResult().length() == paramConfig.getStrLength()) {
                System.out.println("执行时间" + (System.currentTimeMillis() - startTime));
                String result = rxtxManager.stringToComma(cache.getResult());
                cache.setResult("");
                return result;
            }
            if (System.currentTimeMillis() - startTime >= 2000)
            {

                System.out.println("结束时间"+System.currentTimeMillis()+"  开始时间"+startTime+"  超时时间"+(System.currentTimeMillis() - startTime));
                cache.setResult("");
                throw new ComException("机器响应超时");
            }
            Thread.sleep(10);
        }
    }
}
